package com.nd.android.musicboxlibrary.util;

import java.lang.reflect.Method;

import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.common.StarAppConst;

public class TypefaceUtil {

	private TypefaceUtil() {}
	
	/**
	 * 递归设置View的字体
	 * @author 			DingXiaohui
	 * @date 				2014-11-13 下午6:48:51
	 * @description 	
	 * @param rootView
	 */
	public static void setFontRecursion(ViewGroup rootView) {
		if (rootView == null) {
			return;
		}

		if (rootView.getChildCount() == 0) {
			return;
		}

		for (int i = 0; i < rootView.getChildCount(); i++) {
			View child = rootView.getChildAt(i);
			if (child == null) {
				continue;
			}

			if (child instanceof ViewGroup) {
				setFontRecursion((ViewGroup) child);
			} else {
				setViewTypefaceIfAllow(child);
			}
		}
	}
	
	/**
	 * 通过反射的方式设置View的字体
	 * @author 			DingXiaohui
	 * @date 				2014-11-13 下午6:49:04
	 * @description 	
	 * @param view
	 */
	public static void setViewTypefaceIfAllow(View view) {
		if ( view != null && 
				( view instanceof TextView || // 此处可以扩展要更改字体的控件类型
						view instanceof Button ) ) {
			Typeface font = StarAppConst.getInstance().getLTXTypeface();
			Class<?> clazz = view.getClass();
			final String methodName = "setTypeface";
			Class<?>[] args = new Class[] { Typeface.class };
			
			Method method = null;
			try {
				method = clazz.getDeclaredMethod( methodName, args );
			} catch (NoSuchMethodException e) {
			}
			
			if ( method == null ) {
				try {
					method = clazz.getMethod( methodName, args );
				} catch (NoSuchMethodException e) {
				}
			}
			
			if ( method != null ) {
				try {
					method.invoke( view, new Object[] { font } );
				} catch (Exception e) {
				}
			}
		}
	}
	
}
